package com.sskj.zixun.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.just.agentweb.AgentWeb;

import com.sskj.zixun.R;
import com.sskj.zixun.bean.Notice;
import com.sskj.zixun.http.HttpConfig;
import com.sskj.zixun.presenter.WebViewActivityPresenter;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;

@Route(path = RConfig.GONGGAO_DETAIL)//公告详情
public class WebViewActivity extends BaseActivity<WebViewActivityPresenter> {
    @BindView(com.sskj.zixun.R2.id.webView)
    WebView webView;
    @BindView(com.sskj.zixun.R2.id.ll_web)
    LinearLayout llWeb;
    @BindView(com.sskj.zixun.R2.id.tvTitle)
    TextView tvTitle;
    @BindView(com.sskj.zixun.R2.id.ivBack)
    ImageView ivBack;

    private AgentWeb mAgentWeb;
    @Autowired
    public String noticeId;


    @Override
    protected int getLayoutResId() {
        return R.layout.zixun_activity_web_view;
    }

    @Override
    public WebViewActivityPresenter getPresenter() {
        return new WebViewActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        ClickUtil.click(ivBack, () -> {
            finish();
        });
        tvTitle.setText(App.INSTANCE.getString(R.string.zixunWebViewActivity0));
//        noticeId = getIntent().getStringExtra(Constans.INTENT_NOTICE_ID);
        mPresenter.getData(noticeId);
        initWeb();
    }

    private void initWeb() {

        ((ViewGroup) (webView.getParent())).removeView(webView);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");//设置默认为utf-8
        mAgentWeb = AgentWeb.with(this)//这里需要把 Activity 、 和 Fragment  同时传入
                .setAgentWebParent(llWeb, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator(Color.TRANSPARENT)// 使用默认进度条
                .setWebView(webView)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                .createAgentWeb()
                .ready()
                .go("");
    }


    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
//
//            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams();
//            params.width = ScreenUtils.getScreenWidth(WebViewActivity.this);
//            params.height = ScreenUtils.getScreenHeight(WebViewActivity.this) - webView.getTop();
//            webView.setLayoutParams(params);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

        }
    };

    /**
     * 开启web页面
     *
     * @param context
     */
    public static void start(Context context, String noticeId) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constans.INTENT_NOTICE_ID, noticeId);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
//        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
        return true;
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

    public void loadData(Notice datas) {
        String content = formatImg(datas.getContent().replaceAll("<span.*?</span><span.*?</span>", ""));
        content = "<font style=\"color:white;font-size:24px\">" + datas.getTitle() + "</font><br>\n" +
                "<div style=\"text-align:right;margin-top:10px;color:#bbbbbb\">" + datas.getTime() + "</div><br>"
                + "<hr size='0.1px',style=\"background-color:#7591b4\"></hr>"
                + "<div style=\"margin-top:1px;color:#ffffff\">" + content + "</div" +
                ">";
        content = "<body style=\"background:#141724;margin:0;padding-left:15px;padding-right:15px;margin-top:20px\">" + content + "</body" +
                ">";
        mAgentWeb.getUrlLoader().loadData(content, "text/html; charset=UTF-8", null);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    public String formatImg(String content) {
        Document document = Jsoup.parse(content);
        Elements imgs = document.getElementsByTag("img");
        for (int i = 0; i < imgs.size(); i++) {
            Element img = imgs.get(i);
            img.attr("width", "100%").attr("height", "auto");
            String url = img.attr("src");
            if (!url.contains("http")) {
                url = HttpConfig.BASE_URL + url;
            }
            img.attr("src", url);
        }
        return document.toString();
    }


}
